﻿using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TextCompare
{
    class HtmlFormatter : IFormatter
    {
        public HtmlFormatter()
        {
        }

        public string HtmlContent { get { return htmlContent; } }

        public void Write(ITextMatcher textMatcher, IEnumerable<MatchPoint> points)
        {
            if (textMatcher.SourceCount == 0 || textMatcher.TargetCount == 0 || points == null)
                return;

            if (points.Count() == 0)
            {
                WriteAll(textMatcher.Source, textMatcher.Target);
                return;
            }

            WriteByPoint(textMatcher, points);
        }

        private void WriteAll(string source, string target)
        {
            StringBuilder html = new StringBuilder();
            html.AppendFormat(styles[Direction.Right], target);
            html.AppendFormat(styles[Direction.Down], source);
            htmlContent = html.ToString();
        }

        private void WriteByPoint(ITextMatcher textMatcher, IEnumerable<MatchPoint> points)
        {
            StringBuilder html = new StringBuilder();
            foreach (var point in points)
            {
                switch (point.Direction)
                {
                    case Direction.DownRight:
                        html.AppendFormat(styles[Direction.DownRight], textMatcher.GetSourceSubString(point.X, point.Y));
                        break;
                    case Direction.Down:
                        html.AppendFormat(styles[Direction.Down], textMatcher.GetSourceSubString(point.X, point.Y));
                        break;
                    case Direction.Right:
                        html.AppendFormat(styles[Direction.Right], textMatcher.GetTargetSubString(point.X, point.Y));
                        break;
                    default:
                        break;
                }
            }

            htmlContent = html.ToString();
        }

        private string htmlContent;

        private static Dictionary<Direction, string> styles = new Dictionary<Direction, string>()
        {
            { Direction.Down,"<span style='background:#32CD32;color=#000000'>{0}</span>" },
            { Direction.Right,"<del style='color=#FF0000'>{0}</del>"},
            { Direction.DownRight,"<span style='color=#000000'>{0}</span>"}
        };
    }
}
